package com.devunion.bogdan.model.project.dao;

import com.devunion.bogdan.model.project.*;
import com.devunion.bogdan.persistence.BaseDaoObject;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Hibernate;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.apache.commons.lang.StringUtils;

import java.io.Serializable;
import java.util.*;


/**
 * <p>Hibernate implementation of <code>UserDao</code></p>
 *
 * @author Viktar Liaskovich
 */
public class HibernateUserDao extends BaseDaoObject<User> implements UserDao {

    /**
     * {@inheritDoc}
     */
    public User getByKey(Serializable key) {
        return (User) hibernateTemplate.get(User.class, key);
    }

    /**
     * {@inheritDoc}
     */
    public List<User> loadAll() {
        return hibernateTemplate.loadAll(User.class);
    }

    public User getUser(final String login, final String password) {
        if (StringUtils.isEmpty(login) || StringUtils.isEmpty(password)) {
            return null;
        }

        return (User) hibernateTemplate.execute(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException {
                List list = session.createQuery("from User u where u.login = :login and u.password = :password")
                        .setParameter("login", login, Hibernate.STRING)
                        .setParameter("password", password, Hibernate.STRING).list();

                return list.isEmpty() ? null : list.get(0);
            }
        });
    }
}